package com.example.myfirstapplication

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.example.myfirstapplication.utils.BaseActivity
import com.example.myfirstapplication.utils.FileOP
import com.example.myfirstapplication.utils.goActivity
import com.example.myfirstapplication.utils.myToast
import kotlinx.android.synthetic.main.activity_fileop_layout.*

class FileOPActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fileop_layout)

        btnSave.setOnClickListener {
            val myData = myDataET.text.toString()//fun save
            FileOP().save(this, "myData.txt", myData)
        }
        btnRead.setOnClickListener {
            val str = FileOP().read(this, "myData.txt")//fun load
            myDataET.setText(str)
        }
        val mySPF = getSharedPreferences("mySPF", Context.MODE_PRIVATE)
        //val spfEdit = getSharedPreferences("mySPF", Context.MODE_PRIVATE).edit()

        btnReadSPF.setOnClickListener {
            val name = mySPF.getString("name", "")
            val age = mySPF.getInt("age", 0)
            val married = mySPF.getBoolean("married", false)
            val out = "name:$name \n age:$age \n married:$married"
            myToast(this, out)
        }
        btnWriteSPF.setOnClickListener {
            /*val spfEdit = mySPF.edit()
            spfEdit.putString("name", "Nelson")
            spfEdit.putInt("age", 34)
            spfEdit.putBoolean("married", true)
            spfEdit.apply()*/
            getSharedPreferences("mySPF", Context.MODE_PRIVATE).edit {
                putString("name", "Nelson")
                putInt("age", 30)
                putBoolean("married", true)
            }
            myToast(this, "SPF保存成功")
        }
        btnToLogin.setOnClickListener {
            goActivity(this, LoginActivity::class.java)
        }
        btnToDB.setOnClickListener {
            goActivity(this, DatabaseActivity::class.java)
        }
    }

/*    private fun save(inputText: String) {
        try {
            val output = openFileOutput("myData.txt", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputText)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun load(): String {
        val content = StringBuilder()
        try {
            val input = openFileInput("myData.txt")
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return content.toString()
    }*/
}